package com.adv.controller.base;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.adv.service.UserService;
import com.adv.util.Constant;
import com.adv.util.MailUtil;
import com.adv.util.PropertiesUtil;
import com.adv.util.RequestUtil;
import com.adv.vo.LoginForm;
import com.adv.vo.MailInfo;
import com.adv.vo.UserForm;
import com.adv.vo.group.Insert;
import com.adv.vo.group.Update;

/**
 * 登录控制器
 * 
 * @author WUQINGLONG
 *
 */
@Controller
public class UserController extends BaseController {

	@Autowired
	private UserService service;

	@Autowired
	private MailUtil mailUtil;

	/**
	 * 登录处理器<br />
	 * 
	 * GET请求显示登录页面<br />
	 * POST请求提交登录
	 * 
	 * @param form
	 *            登录参数
	 * @param result
	 *            登录参数自动校验结果
	 * @param model
	 *            返回页面值域
	 * @return 返回页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/login")
	public String login(@Valid LoginForm form, BindingResult result, ModelMap model) {
		if (RequestUtil.isPost()) {
			Map<String, Object> errorMap = new HashMap<String, Object>();
			if (!form.getKaptcha().equalsIgnoreCase((String) RequestUtil.getSession().getAttribute(Constant.KAPTCHA))) {
				errorMap.put("kaptcha", "验证码错误");
			} else if (result.hasErrors()) {
				errorMap.putAll((Map<String, Object>) convertField2Map(result).get("msg"));
			} else {
				errorMap.putAll(service.login(form));
			}
			if (SecurityUtils.getSubject().isAuthenticated()) {
				// 发送邮件demo
				String address = PropertiesUtil.get("mail.username");
				MailInfo mail = new MailInfo();
				mail.setContendId(new Random().nextInt(100) + "");
				mail.setContent(
						form.getUsername() + " logined system in " + Constant.SDFCOMMON.format(new Date()));
				mail.setSubject("login");
				mail.setSender(address);
				mail.setReceivers(new String[] { address });
				mailUtil.send(mail);
				return redirect("main");
			}
			model.put("error", errorMap);
			model.put("user", form);
		} else if (RequestUtil.isGet()) {
			if (SecurityUtils.getSubject().isAuthenticated()) {
				return redirect("main");
			}
		}
		return "user/login";
	}

	/**
	 * 登出处理器
	 * 
	 * @return
	 */
	@RequestMapping("/loginout")
	public String loginout() {
		service.loginout();
		return redirect("login");
	}

	@RequestMapping("/user/list")
	public Object list() {
		return "user/list";
	}

	/**
	 * 获取完整json格式的数据
	 * 
	 * @return json
	 */
	@ResponseBody
	@RequestMapping("/user/json")
	public Object json() {
		return service.getUser();
	}

	@RequestMapping("/user/add")
	public String add(UserForm form, ModelMap model) {
		model.put("user", service.initForm(form));
		return "user/modify";
	}

	@ResponseBody
	@RequestMapping("/user/save")
	public Object save(@Validated(Insert.class) UserForm form, @Valid BindingResult result, ModelMap model) {
		if (result.hasErrors()) {
			// 新建需要校验完整字段
			return convertField2Map(result);
		}
		return service.saveUser(form);
	}

	@ResponseBody
	@RequestMapping("/user/update")
	public Object update(@Validated(Update.class) UserForm form, @Valid BindingResult result, ModelMap model) {
		return save(form, result, model);
	}

}
